home *** CD-ROM | disk | FTP | other *** search
/ Reverse Code Engineering RCE CD +sandman 2000 / ReverseCodeEngineeringRceCdsandman2000.iso / RCE / Ebooks / Thinking in C++ V2 / C25 / DoubleDispatch.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  2000-05-25  |  1.5 KB  |  53 lines

  1. //: C25:DoubleDispatch.cpp
  2. // From Thinking in C++, 2nd Edition
  3. // Available at http://www.BruceEckel.com
  4. // (c) Bruce Eckel 1999
  5. // Copyright notice in Copyright.txt
  6. //{L} DDTrashPrototypeInit
  7. //{L} fillBin Trash TrashStatics
  8. // Using multiple dispatching to handle more than
  9. // one unknown type during a member function call
  10. #include "TypedBin.h"
  11. #include "fillBin.h"
  12. #include "sumValue.h"
  13. #include "../purge.h"
  14. #include <iostream>
  15. #include <fstream>
  16. using namespace std;
  17. ofstream out("DoubleDispatch.out");
  18.  
  19. class TrashBinSet : public vector<TypedBin*> {
  20. public:
  21.   TrashBinSet() {
  22.     push_back(new BinOf<DD<Aluminum> >());
  23.     push_back(new BinOf<DD<Paper> >());
  24.     push_back(new BinOf<DD<Glass> >());
  25.     push_back(new BinOf<DD<Cardboard> >());
  26.   };
  27.   void sortIntoBins(vector<Trash*>& bin) {
  28.     vector<Trash*>::iterator it;
  29.     for(it = bin.begin(); it != bin.end(); it++)
  30.       // Perform the double dispatch:
  31.       if(!(*it)->addToBin(*this))
  32.         cerr << "Couldn't add " << *it << endl;
  33.   }
  34.   ~TrashBinSet() { purge(*this); }
  35. };
  36.  
  37. int main() {
  38.   vector<Trash*> bin;
  39.   TrashBinSet bins;
  40.   // fillBin() still works, without changes, but
  41.   // different objects are cloned:
  42.   fillBin("Trash.dat", bin);
  43.   // Sort from the master bin into the
  44.   // individually-typed bins:
  45.   bins.sortIntoBins(bin);
  46.   TrashBinSet::iterator it;
  47.   for(it = bins.begin(); it != bins.end(); it++)
  48.     sumValue(**it);
  49.   // ... and for the master bin
  50.   sumValue(bin);
  51.   purge(bin);
  52. } ///:~
  53.